package com.maoning.ware.service.impl;

import com.maoning.common.utils.R;
import com.maoning.ware.feign.ProductFeignService;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.QEncoderStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoning.common.utils.PageUtils;
import com.maoning.common.utils.Query;

import com.maoning.ware.dao.WareSkuDao;
import com.maoning.ware.entity.WareSkuEntity;
import com.maoning.ware.service.WareSkuService;
import org.springframework.util.CollectionUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        skuId:
//        wareId:
        final QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        final String skuId = (String) params.get("skuId");
        if(StringUtils.isNotEmpty(skuId)){
            queryWrapper.and((w) -> {
                w.eq("sku_id", skuId).or().like("sku_name", skuId);
            });
        }
        final String wareId = (String) params.get("wareId");
        if(StringUtils.isNotEmpty(wareId)){
            queryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        final List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("ware_id", wareId).eq("sku_id", skuId));
        if(CollectionUtils.isEmpty(wareSkuEntities)){
            final WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);

//            远程查询sku的名字,如果失败也不需要回滚
            try {
                final R r = productFeignService.skuInfo(skuId);
                final Map<String,Object> skuInfo = (Map<String, Object>) r.get("skuInfo");
                final String skuName = (String) skuInfo.get("skuName");
                wareSkuEntity.setSkuName(skuName);
            } catch (Exception e) {
                e.printStackTrace();
            }

            wareSkuDao.insert(wareSkuEntity);
        }else {
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

}